﻿#include "NosepieceB140.h"
#include <QDebug>
NosepieceB140::NosepieceB140(DMC_B140_M *card, QObject *parent)
    : QObject(parent)
{
    m_card = card;
    m_lens = 0;
    m_steps = 20000; //默认 20000 步转 72°，也就是转一颗物镜。

    m_timer = new QTimer(this);
    m_timer->setInterval(200);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimer()));
    m_timer->start();
}

void NosepieceB140::onTimer()
{
    if(m_card->isMoving(3)) return;
    int n = m_card->readIOPort();
    //qDebug() << (n & 0b01100000);
    if((n & 0b01100000) == 0b01000000)
    {
        nextPos();
    }
    else if((n & 0b01100000) == 0b00100000)
    {
        previousPos();
    }
}

void NosepieceB140::setInitLens(int pos)
{
    m_lens = qBound(0, pos, 4);
    if(m_card)
    {
        m_card->setTheoryPos(3, m_lens * m_steps);
    }
    emit changeLens(-1, m_lens);
}

void NosepieceB140::attach(DMC_B140_M *card)
{
    m_card = card;
    m_lens = 0;
}

void NosepieceB140::loadSettings(QSettings &settings)
{
    int lens = settings.value("Nosepiece/LENS", 0).toInt();
    m_steps = settings.value("Nosepiece/Step", 20000).toInt();
    qDebug() << "Nosepiece/LENS = " << lens;
    setInitLens(lens);

}

void NosepieceB140::writeSettings(QSettings &settings)
{
    settings.setValue("Nosepiece/LENS", m_lens);
}

void NosepieceB140::nextPos()
{
    if(m_lens == -1) return; //转盘没有初始化，不动作
    if(m_lens <= 3)
    {
        int newLens = m_lens + 1;
        setLens(newLens);
    }
}

void NosepieceB140::previousPos()
{
    if(m_lens == -1) return; //转盘没有初始化，不动作
    if(m_lens >= 1)
    {
        int newLens = m_lens - 1;
        setLens(newLens);
    }
}

void NosepieceB140::goHome()
{
    m_lens = 0;
    if(m_card)
    {
        qDebug() << "goHome(AXIS_W, 10000)";
        m_card->goHome(3, 10000);     
    }
}

void NosepieceB140::setLens(int oldLens, int newLens)
{
    if(newLens == m_lens) return; // 这时不需要做任何操作
    if(oldLens == -1)
    {
        setInitLens(newLens);// 说明这是设备启动时初始化物镜位置。
        return;
    }
    if(m_lens != oldLens)
    {
        qWarning() << "Nosepiece positon error!";
        return;
    }
    setLens(newLens);
}
void NosepieceB140::setLens(int newLens)
{
    if(newLens == m_lens) return;

    int old = m_lens;
    m_lens = newLens;
    if(m_card)
    {
        qDebug() << "moveTo(3, " << m_steps * newLens << ")";
        m_card->setSpeed(3, 10000);
        m_card->moveTo(3, m_steps * newLens);
        emit changeLens(old, newLens);
    }
}
